import { Component, OnInit } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'car-insurance',
  templateUrl: './car-insurance.component.html',
  styleUrls: ['./car-insurance.component.scss'],
})
export class CarInsuranceComponent implements OnInit {

  // 车险分析


  // 销售
  salesField: FormlyFieldConfig[] = [
    {
      key: 'SUPPLIER',
      type: 'select',
      templateOptions: {
        label: '保险公司',
        api: 'cm.partyRole.findAll',
        domain: '{"filters":[{"field":"role.id","operator":"EQ","value":"Supplier"}],"groups":[{"filters":[{"field":"id","operator":"EQ","value":"{{value}}"},{"field":"party.name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}],"operator":"and"}',
        downFormatter: '"["+ value.id + "]" + value.name',
        valueFormatter: '"["+ value.id + "]" + value.name',
        divCol: 5,
        addSame: 'false',
        uniqueKey: 'id',
        multiple: 'true',
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  salesModel: any = {};

  // 饼图
  salesPieOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showTooltip,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
    },
    series: [
      {
        name: '销售金额', type: 'pie', center: ['60%', '50%'], radius: '50%', emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  salesPieData: any;
  salesPieLoading: boolean = false;

  // 柱形图
  salesBarOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['商业险金额', '交强险金额'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '金额',
        type: 'value',
        axisLabel: {
          formatter: '{value}',
        },
      },
    ],
    series: [
      { name: '商业险金额', type: 'bar', stack: '金额', emphasis: { focus: 'series' } },
      { name: '交强险金额', type: 'bar', stack: '金额', emphasis: { focus: 'series' } },
    ],
  };
  salesBarData: any;
  salesBarLoading: boolean = false;

  // 表格
  salesFormData: any;
  salesFormLoading: boolean = false;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {
      this.refreshSalesData();
    }, 1000);
  }

  showTooltip(params) {
    let tooltip = params.seriesName + '<br/>' + params.name + ':' + params.data[1] + '(' + params.percent + '%)';
    return tooltip;
  }

  refreshSalesData() {
    let date = this.bi.conversionMonth(this.salesModel['DATE']);
    let nowDate = this.bi.currentMonthsList(date);
    let id = this.salesModel['SUPPLIER'] ? this.salesModel['SUPPLIER'] : [];

    const data = {
      SUPPLIER: id,
      DATE_START: nowDate[0],
      DATE_END: nowDate[1],
    };

    let pieApi = 'businessControl.insuranceSalePieChart';

    this.salesPieLoading = true;
    this.apiService.post(pieApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('车险销售分析-饼图', body);
      let dimensions = [];
      let source = [];
      if (body && body.length != 0) {
        body.forEach((res) => {
          dimensions.push(res['CLASS_NAME']);
          source.push([
            res['CLASS_NAME'],
            res['AMOUNT'],
          ]);
        });
      }
      this.salesPieData = {
        dataset: {
          dimensions: dimensions,
          source: source,
        },
      };
      this.salesPieLoading = false;
    });

    let barApi = 'businessControl.insuranceSaleBarChart';

    this.salesBarLoading = true;
    this.apiService.post(barApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('车险销售分析-柱形图', body);
      // let dimensions = [];
      let source = [['INSURANCE_COMPANY', 'COMMERCIAL_INSURANCE', 'COMPULSORY_INSURANCE']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['INSURANCE_COMPANY']);
          source.push([
            res['INSURANCE_COMPANY'],
            res['COMMERCIAL_INSURANCE'],
            res['COMPULSORY_INSURANCE'],
          ]);
        });
      }
      this.salesBarData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.salesBarLoading = false;
    });

    let formApi = 'businessControl.insuranceSaleFrom';

    this.salesFormLoading = true;
    this.salesFormData = [];
    this.apiService.post(formApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('车险销售分析-表格', body);
      if (body && body.length != 0) {
        this.salesFormData = body;
      }
      this.salesFormLoading = false;
    });
  }

}

